package com.example.sign.view
import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.BaseApp
import com.example.lib_base.BaseTitle
import com.example.lib_base.UIState
import com.example.lib_http.Const
import com.example.sign.SignIntent
import com.example.sign.SignViewModel

import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.LocalTime
import java.util.Timer
import kotlin.concurrent.timerTask

//计时器
lateinit var timer: Timer

//地图对象
lateinit var map: AMap

//地图的view
lateinit var mapVIew: MapView

//定位的设置
lateinit var myLocationStyle: MyLocationStyle

//地理位置信息检索
lateinit var geocodeSearch: GeocodeSearch

//地理位置信息查询
lateinit var query: RegeocodeQuery

@RequiresApi(Build.VERSION_CODES.O)
@Composable
//fun SignCommitPage(navHostController: NavHostController) {
fun SignCommitPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {
   // Column(Modifier.padding(10.dp)) {

    //上班打卡显示时间
    var startTime by remember {
        mutableStateOf("上班还未打卡")
    }

    //下班打卡显示时间
    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }

    //按钮文字
    var btnName by remember {
        mutableStateOf("上班打卡")
    }

    //按钮计时时间
    var nowTime by remember {
        mutableStateOf("00:00:00")
    }

    //控制是否按钮可点击
    var enable by remember {
        mutableStateOf(true)
    }

    //存储
    val kv = MMKV.defaultMMKV()

    var lat = 0.0
    var lon = 0.0
    var type = ""
    var status = ""
    var address = ""


    LaunchedEffect(key1 = "", block = {
        //计时的协程,获取当前时间
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                nowTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            }, 0, 1000)
        }

        launch {
            //取出上班打卡的时间
            val signTime = kv.decodeString(Const.PARAM_SIGN_IN, "").toString()
            //如果上班打卡不为空,说明打卡过
            if (!TextUtils.isEmpty(signTime)) {
                //获取当前日期
                val time = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                //截取当前日期
                val signDate = signTime.substring(0, 10)
                //说明打卡的时间是今天
                if (time == signDate) {
                    startTime = "上班时间 : $signTime"
                    //取出下班时间
                    val outTime = kv.decodeString(Const.PARAM_SIGN_OUT, "")
//                    val outDate = outTime?.substring(0, 10)
//                    if (time == outDate) {
//                        endTime = "下班时间 : $outTime"
//                        //今天的上班和下班都打过卡了,所以设置按钮不可用
//                        enable = false
                    if (!outTime.isNullOrEmpty()) {
                        val outDate = outTime?.substring(0, 10)
                        if (time == outDate) {
                            endTime = "下班时间 : $outTime"
                            //今天的上班和下班都打过卡了,所以设置按钮不可用
                            enable = false
                        }
                    } else {
                        //如果下班卡不是今天
                        btnName = "下班打卡"
                    }
                }
            }
        }
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "添加签到信息失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        ToastUtils.showLong("签到/签退成功")
                        navHostController.popBackStack()
                    }
                }
            }
        }
    })

    Column(Modifier.padding(10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        BaseTitle(title = "签到", navHostController = navHostController)
        AndroidView(modifier = Modifier.height(300.dp), factory = {
            mapVIew = MapView(it)
            mapVIew.onCreate(null)

            map = mapVIew.map
            myLocationStyle = MyLocationStyle()
            //定位刷新时间,每2秒定位一次
            myLocationStyle.interval(2000)
            map.myLocationStyle = myLocationStyle
            //设置定位开关打开
            map.isMyLocationEnabled = true


//            map.addOnMyLocationChangeListener {
//                Log.i("TagA", "维度:${it.latitude},经度:${it.longitude}")
                map.addOnMyLocationChangeListener { location ->
                    lon = location.longitude
                    lat = location.latitude
                geocodeSearch = GeocodeSearch(BaseApp.context)

                //query = RegeocodeQuery(LatLonPoint(it.latitude, it.longitude), 200f, GeocodeSearch.AMAP)
                    query = RegeocodeQuery(LatLonPoint(location.latitude, location.longitude), 200f, GeocodeSearch.AMAP)
                geocodeSearch.getFromLocationAsyn(query)
                geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(result: RegeocodeResult?, errorCode: Int) {
                        //Log.i("TagA", "定位地址:${result?.regeocodeAddress?.formatAddress}")
                        address = "${result?.regeocodeAddress?.formatAddress}"
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                    }
                })
            }

            mapVIew
        })

        Spacer(modifier = Modifier.height(50.dp))
        Text(
            text = startTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Text(
            text = endTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Button(modifier = Modifier
            .size(140.dp)
            .clip(CircleShape), enabled = enable, onClick = {
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
            val workTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            if (btnName == "上班打卡") {
                kv.encode(Const.PARAM_SIGN_IN, time)
               // startTime = "上班时间 : $time"
                val workStart = LocalTime.of(8, 0) //上班时间
//                startTime = if (LocalTime.parse(workTime).isAfter(workStart)) {
//                    "上班时间 : $time 迟到"
                if (LocalTime.parse(workTime).isAfter(workStart)) {
                    status = "迟到"
                    startTime = "上班时间 : $time 迟到"
                } else {
                   // "上班时间 : $time 打卡正常"
                    status = "正常"
                    startTime = "上班时间 : $time 打卡正常"
                }
                type = "上班"
                btnName = "下班打卡"

                val map = mapOf(
                    Const.PARAM_SIGN_LAT to lat,
                    Const.PARAM_SIGN_LON to lon,
                    Const.PARAM_SIGN_TYPE to type,
                    Const.PARAM_SIGN_ADDRESS to address,
                    Const.PARAM_SIGN_STATUS to status,
                )
                vm.sendIntent(SignIntent.AddSign(map))
            } else {
                kv.encode(Const.PARAM_SIGN_OUT, time)
                //endTime = "下班时间 : $time"
                val workEnd = LocalTime.of(17, 0) //上班时间
//                endTime = if (LocalTime.parse(workTime).isBefore(workEnd)) {
//                    "下班时间 : $time 早退"
                if (LocalTime.parse(workTime).isBefore(workEnd)) {
                    status = "早退"
                    endTime = "下班时间 : $time 早退"
                } else {
                   // "下班时间 : $time 打卡正常"
                    status = "正常"
                    endTime = "下班时间 : $time 打卡正常"
                }
                type = "下班"
                enable = false
                val map = mapOf(
                    Const.PARAM_SIGN_LAT to lat,
                    Const.PARAM_SIGN_LON to lon,
                    Const.PARAM_SIGN_TYPE to type,
                    Const.PARAM_SIGN_ADDRESS to address,
                    Const.PARAM_SIGN_STATUS to status,
                )
                vm.sendIntent(SignIntent.AddSign(map))
            }

        }) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }


    }


}